<template>
  <el-dialog v-model="visible" :title="`新增下一级设备 - ${parentItem?.name || '根'}`" width="100%" top="5vh">
    <div class="table-wrapper" ref="tableWrapper">
      <el-table :data="rows" border style="width: 100%" :header-cell-style="{ background: '#f9fafb', fontWeight: 600 }">
        <el-table-column prop="parentName" label="上一级名称" min-width="160">
          <template #default="{ row, $index }">
            <el-select v-model="row.parentName" placeholder="请选择上一级名称">
              <el-option
                v-for="opt in getParentNameOptions(row.nodeType, $index)"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
              />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column prop="nodeType" label="类型" min-width="120">
          <template #default="{ row, $index }">
            <el-select v-model="row.nodeType" @change="onTypeChange($index)">
              <el-option
                v-for="opt in getTypeOptions()"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
              />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column prop="name" label="名称" min-width="150">
          <template #default="{ row }">
            <el-input v-model="row.name" />
          </template>
        </el-table-column>

        <el-table-column prop="beType" label="类别" min-width="120">
          <template #default="{ row }">
            <el-input v-model="row.beType" />
          </template>
        </el-table-column>

        <el-table-column prop="area" label="区域" min-width="120">
          <template #default="{ row }">
            <el-input v-model="row.area" />
          </template>
        </el-table-column>

        <el-table-column label="操作" width="260" fixed="right">
          <template #default="{ row, $index }">
            <el-button link type="primary" @click="copyRow($index)">复制</el-button>
            <el-button link type="warning" @click="clearRow($index)">清空</el-button>
            <el-button link type="danger" @click="removeRow($index)">删除</el-button>
            <el-button link type="success" @click="openChildDialog(row)">编辑子级</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="add-btn">
      <el-button type="success" plain size="small" @click="addRow">＋ 新增一行</el-button>
      <el-button type="info" plain size="small" @click="scrollToLeft">⬅ 回到最左边</el-button>
    </div>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="confirm">确定</el-button>
    </template>

    <!-- 子级编辑弹窗（递归使用自己） -->
    <DeviceLayerTable ref="childDialog" @confirm="onChildConfirm" />
  </el-dialog>
</template>

<script setup>
import { ref, reactive, nextTick, watch } from "vue";
import { ElMessage } from "element-plus";

// 引用自身（递归组件）
import DeviceLayerTable from "@/components/sbtz/node/DeviceLayerTable.vue"; // ⚠️ 把文件名改为你自己的.vue文件名

const emit = defineEmits(["confirm"]);

const visible = ref(false);
const rows = reactive([]);
const parentItem = ref(null);
const tableWrapper = ref(null);
const childDialog = ref(null);

const ORDER = ["SYSTEM", "MACHINE", "MODULE", "COMPONENT", "PART"];

const lastCache = reactive({});
const cacheKey = ref("");

function open(item) {
  visible.value = true;
  parentItem.value = item || {};

  const key = `${item.nodeType}_${item.uid || item.id || Date.now()}`;
  cacheKey.value = key;

  if (lastCache[key]) {
    rows.splice(0, rows.length, ...JSON.parse(JSON.stringify(lastCache[key])));
  } else {
    rows.splice(0, rows.length);
    rows.push(makeEmptyRow(item.name, nextType(item.nodeType)));
  }

  nextTick(() => {
    rows.forEach((r, index) => {
      if (!getTypeOptions().some(opt => opt.value === r.nodeType)) {
        r.nodeType = getTypeOptions()[0]?.value || "";
      }
      if (!getParentNameOptions(r.nodeType, index).some(opt => opt.value === r.parentName)) {
        r.parentName = getParentNameOptions(r.nodeType, index)[0]?.value || "";
      }
    });
  });
}

function nextType(type) {
  const idx = ORDER.indexOf(type);
  return ORDER[idx + 1] || "PART";
}

function getTypeOptions() {
  const pType = parentItem.value?.nodeType || "";
  switch (pType) {
    case "MACHINE":
      return [
        { label: "子设备", value: "MODULE" },
        { label: "部件", value: "COMPONENT" },
        { label: "零件", value: "PART" },
      ];
    case "MODULE":
      return [
        { label: "部件", value: "COMPONENT" },
        { label: "零件", value: "PART" },
      ];
    case "COMPONENT":
      return [{ label: "零件", value: "PART" }];
    default:
      return [
        { label: "子设备", value: "MODULE" },
        { label: "部件", value: "COMPONENT" },
        { label: "零件", value: "PART" },
      ];
  }
}

function getParentNameOptions(nodeType, index) {
  const options = [];
  const parentName = parentItem.value?.name?.trim();
  if (parentName) options.push({ label: parentName, value: parentName });
  if (nodeType === "COMPONENT") {
    rows.forEach((row, i) => {
      if (i < index && row.nodeType === "MODULE" && row.name?.trim()) {
        options.push({ label: row.name, value: row.name });
      }
    });
  } else if (nodeType === "PART") {
    rows.forEach((row, i) => {
      if (i < index && (row.nodeType === "COMPONENT" || row.nodeType === "MODULE") && row.name?.trim()) {
        options.push({ label: row.name, value: row.name });
      }
    });
  }
  if (!options.length) options.push({ label: parentName || "无", value: parentName || "" });
  return options;
}

function makeEmptyRow(parentName, forcedType) {
  return {
    uid: Math.random().toString(36).slice(2),
    parentName,
    nodeType: forcedType,
    name: "",
    beType: "",
    area: "",
    children: [], // ✅ 新增：用于存放子级
  };
}

function addRow() {
  const last = rows[rows.length - 1];
  const next = last?.nodeType === "PART" ? "PART" : nextType(last?.nodeType);
  const parentName = parentItem.value?.name || "";
  rows.push(makeEmptyRow(parentName, next));
}

function copyRow(i) {
  const newRow = JSON.parse(JSON.stringify(rows[i]));
  newRow.uid = Math.random().toString(36).slice(2);
  rows.splice(i + 1, 0, newRow);
}

function clearRow(i) {
  const type = rows[i].nodeType;
  const parentName = rows[i].parentName;
  rows[i] = makeEmptyRow(parentName, type);
}

function removeRow(i) {
  if (rows.length <= 1) return ElMessage.warning("至少保留一行");
  rows.splice(i, 1);
}

function scrollToLeft() {
  nextTick(() => {
    if (tableWrapper.value) tableWrapper.value.scrollLeft = 0;
  });
}

function confirm() {
  for (let i = 0; i < rows.length; i++) {
    const r = rows[i];
    if (!r.parentName?.trim() || !r.name?.trim()) {
      return ElMessage.error(`第 ${i + 1} 行：上一级名称和名称不能为空`);
    }
  }
  if (cacheKey.value) {
    lastCache[cacheKey.value] = JSON.parse(JSON.stringify(rows));
  }
  emit("confirm", JSON.parse(JSON.stringify(rows)));
  visible.value = false;
}

watch(visible, (val) => {
  if (!val && cacheKey.value) {
    lastCache[cacheKey.value] = JSON.parse(JSON.stringify(rows));
  }
});

// ✅ 新增：编辑子级逻辑
function openChildDialog(row) {
  if (!childDialog.value) return;
  childDialog.value.open(row);
}

function onChildConfirm(childRows) {
  const parent = parentItem.value;
  if (!parent.children) parent.children = [];
  parent.children = childRows;
}
defineExpose({ open });
</script>

<style scoped>
.table-wrapper {
  overflow-x: auto;
  border: 1px solid #ebeef5;
  border-radius: 8px;
}
.add-btn {
  text-align: right;
  padding: 10px;
  background: #fafafa;
  border-top: 1px solid #ebeef5;
}
</style>
